package com.unittec.zk.provider.exam.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unittec.zk.provider.exam.entity.ElUserExam;
import com.unittec.zk.provider.exam.mapper.ElUserExamMapper;
import com.unittec.zk.provider.scope.ThreadLocalScope;
import com.unittec.zk.sdk.exam.request.Req201051;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class ElUserExamService extends ServiceImpl<ElUserExamMapper, ElUserExam> {

    /**
     * 我的考试成绩 分页
     *
     * @param req201051
     * @return
     */
    public Object getUserExamPage(Req201051 req201051) {
        //加载一个条件构造器
        LambdaQueryWrapper<ElUserExam> qw = new LambdaQueryWrapper<>();

        qw.apply("uc.id='"+ThreadLocalScope.getAuthData().getUser()+"'");
        //如果‘考试名称’参数不为空，则将其添加到条件构造器中
        if (StrUtil.isNotBlank(req201051.getTitle())) {
            qw.apply("ee.title like '%"+req201051.getTitle()+"%'");
        }
        //根据条件构造器和分页参数，去查询数据库
        Page<Map<String, Object>> page = this.baseMapper.getUserExamPage(new Page<Object>(req201051.getCurrent(), req201051.getSize()), qw);

        //返回结果
        return page;
    }


    public void joinResult(String userId, String examId, Integer score, boolean passed) {
        //查询条件
        QueryWrapper<ElUserExam> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ElUserExam::getUserId, userId)
                .eq(ElUserExam::getExamId, examId);

        ElUserExam record = this.getOne(wrapper, false);
        if(record == null){
            record = new ElUserExam();
            record.setCreateTime(new Date());
            record.setUserId(userId);
            record.setExamId(examId);
            record.setMaxScore(score);
            record.setPassed((byte) (passed?1:0));
            this.save(record);
            return;
        }

        // 修复低分数不加入统计问题
        record.setTryCount(record.getTryCount()+1);

        if(record.getMaxScore() < score){
            record.setMaxScore(score);
            record.setPassed((byte) (passed?1:0));
        }

        this.updateById(record);
    }
}
